<?php

require_once dirname(dirname(__FILE__)) . '/config/ConfigLoader.php';

require_once dirname(dirname(dirname(__FILE__))) . '/function/function_core.php';
require_once dirname(__FILE__) . '/DBManager.php';
require_once getTablesFile() . "/table_application_sensorData.php";
require_once getTablesFile() . "/table_application_nodeArray.php";
require_once getTablesFile() . "/table_application_nodelocalinfo.php";


global $TableSensorDataHeaderArray;
global $TableNodeArrayHeaderArray;
global $TableNodeLocalInfoHeaderArray;

global $head;
$head = array();
global $tableName;

if (isset($_GET['tableName'])) {
    if ($_GET['tableName'] == 'nodearray') {
        $tableName = "table_application_nodeArray";
        $head = $TableNodeArrayHeaderArray;
    } else if ($_GET['tableName'] == 'sensordata') {
        $tableName = "table_application_sensorData";
        $head = $TableSensorDataHeaderArray;
    } else if ($_GET['tableName'] == 'nodelocalinfo') {
        $tableName = "table_application_nodelocalinfo";
        $head = $TableNodeLocalInfoHeaderArray;
    }


    //输出Excel文件头，可把goods.csv换成你要的文件名 
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $_GET['tableName'] . '.csv"');
    header('Cache-Control: max-age=0');

    $data = TableArray($tableName)->fetch_all_data();
    $fp = fopen('php://output', 'a');

    foreach ($head as $i => $v) {
        // CSV的Excel支持GBK编码，一定要转换，否则乱码 
        $head[$i] = iconv('utf-8', 'gbk', $v);
    }
    // 将数据通过fputcsv写到文件句柄 
    fputcsv($fp, $head);
    $row = 0;
    //逐行取出数据，不浪费内存 
    while ($row != count($data)) {
        $row++;
        foreach ($data[$row] as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码 
            $data[$row][$head[$i]] = iconv('utf-8', 'gbk', $v);
        }
        fputcsv($fp, $data[$row]);
    }
    //关闭文件句柄
    fclose($fp);
}
